var  app = getApp();
let keys = '4UTBZ-PUWLX-UGS4R-TIK3C-WFL73-N4FWH';
const tabService = require("../../libs/tabService");
const QQMapWX = require('../../libs/qqmap-wx-jssdk.js');
const qqmapsdk = new QQMapWX({
  key:keys
});
Page({

    /**
     * 页面的初始数据
     */
    data: {
      lineHeight:30,
        cityIndex:0,
        more:1,
        store:[]
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        console.log('-------index/index options-------');
        console.log(options);
        console.log('-------index/index options-------');
        let that=this;      
        var parent_id = options.parent_id;
        var store_id = options.store_id;
      
        if(store_id != undefined){
            this.setData({
                store_id:store_id
              })
              wx.setStorageSync('store_id',store_id);
        }else if(store_id == undefined){
            store_id = 0;
            this.setData({
                store_id:0
              })
            wx.setStorageSync('store_id',0);
         }else{
            store_id = wx.getStorageSync('store_id');  
         }
        if(parent_id!=undefined){
            this.setData({
                parent_id:parent_id
              })
              wx.setStorageSync('parent_id',parent_id);
        }else{
            parent_id = wx.getStorageSync('parent_id');
        
        }
        this.getCity(); 
        var user=wx.getStorageSync('user');
        var open=wx.getStorageSync('open');
        console.log('user=>'+user);
        console.log('open=>'+open);
        if(open==""){
            wx.navigateTo({
              url: '../login/index?parent_id='+parent_id+'&store_id='+store_id,
            })
        }
        if(store_id!=0){
            var role=wx.getStorageSync('role');
            console.log('index+role=>'+role);
            if(role==2){
                wx.reLaunch({
                    url: '../coupon/index?parent_id='+parent_id+'&store_id='+store_id,
                  })
            }else{
                wx.reLaunch({
                    url: '../coupon/index?parent_id='+parent_id+'&store_id='+store_id,
                  })
            }
          
        }
        wx.showShareMenu({
            menus: ['shareAppMessage', 'shareTimeline'],
            success(res) {
              console.log(res)
            },
            fail(e) {
              console.log(e)
            }
          })  
           
        that.setData({
            platform:app.globalData.platform,    
            user:user,
            open:open,
            width:app.globalData.windowWidth,
            height:app.globalData.windowHeight,
            statusBarHeight:app.globalData.statusBarHeight,
            navHeight:app.globalData.navHeight,
            marginTop:app.globalData.navTitleTop,
            domain:app.globalData.platUrl,
            uploadUrl:app.globalData.uploadUrl,
          })
         
    },
    getLocation(){
        let that=this;
        wx.getLocation({
            success: function(res) {
                console.log(res)
                that.setData({
                    lat:res.latitude,
                    lng:res.longitude
                  })
                  wx.setStorageSync('now_lat', res.latitude)
                  wx.setStorageSync('now_lng', res.longitude)
               //that.getDistrict(res.latitude, res.longitude)
               that.getIndex(res.latitude, res.longitude,0,0)
            
            },
            fail(err){
                wx.getSetting({
                     success: (res) => {
                       if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {//非初始化进入该页面,且未授权
                         wx.showModal({
                           title: '是否授权当前位置',
                           content: '需要获取您的地理位置，请确认授权，否则无法获取您所需数据',
                           success: function (res) {
                             if (res.cancel) {
                               wx.showToast({
                                 title: '授权失败',
                                 icon: 'success',
                                 duration: 1000
                               })
                               that.getIndex(0,0)
                             } else if (res.confirm) {
                               wx.openSetting({
                                 success: function (dataAu) {
                                   if (dataAu.authSetting["scope.userLocation"] == true) {
                                     wx.showToast({
                                       title: '授权成功',
                                       icon: 'success',
                                       duration: 1000
                                     })
                                     //再次授权，调用getLocationt的API
                                     //getLoca(that);
                                   } else {
                                     wx.showToast({
                                       title: '授权失败',
                                       icon: 'success',
                                       duration: 1000
                                     })
                                   }
                                 }
                               })
                             }
                           }
                         })
                       } 
                     }
                   })
            }
          });
    },
    getDistrict(latitude, longitude) {
        let that = this;
        wx.request({
          url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${keys}`,
          header: {
            'Content-Type': 'application/json'
          },
          success: function(res) {
            console.log(res.data.result) 
            let data=res.data.result;    
            let now_city = data.address_component.city;
            var city_code=data.ad_info.adcode;    
            let now_lat=data.location.lat;
            let now_lng=data.location.lng;
            var oil_type=that.data.oil_type
            app.globalData.now_city=now_city;
            app.globalData.now_lat=now_lat;
            app.globalData.now_lng=now_lng;
            that.setData({
              city_code:city_code,
              lat:now_lat,
              lng:now_lng
            })
            //app.globalData.lat=;
            wx.setStorageSync('now_city',now_city);
            wx.setStorageSync('now_lat',now_lat);
            wx.setStorageSync('now_lng',now_lng); 
           // that.getStationList(city_code,now_lat,now_lng,oil_type)           
          }
        })
      },
    cityChange:function(e){
        //console.log(e)
        let that=this;
        var index=e.detail.value;
        var cityIndex=this.data.cityIndex;
        var citys=this.data.citys;
        var open=wx.getStorageSync('open');
        var city=citys[index].id;
        if(index>0){
            if(index!=cityIndex){
               // this.getArea()
               wx.request({
                url: app.globalData.platUrl+'store/getArea',
                data:{from:2,user_id:open.user_id,city:city},
                success:res=>{
                    console.log(res);
                    if(res.statusCode==200){
                        let data=res.data;                
                        var area=[];
                        var areas=data.area;
                        console.log(areas);
                        areas.forEach(function(item,index){
                            console.log(item);
                            area[index]=item.city;
                        });
                        console.log(area);
                       
                        
                        that.setData({
                            areas:areas,
                            area:area,
                            list:data.store                              
                       
                        })
                    }else{
                       wx.showLoading({
                         title: '系统错误',
                       }) 
                    }
                }
               })
            }
        }
        var lat=wx.getStorageSync('now_lat');
        var lng=wx.getStorageSync('now_lng')
       // this.storeSearch(lat,lng,city,0);
        this.setData({
            cityIndex:index,
            areaIndex:0
        })
    },
    areaChange:function(e){
        //console.log(e)
        let that=this;
        var index=e.detail.value;
        var areaIndex=this.data.areaIndex;
        var areas=this.data.areas;
        var open=wx.getStorageSync('open');
        var area=areas[index].id;
        if(index>0){
            if(index!=areaIndex){
                var lat=wx.getStorageSync('now_lat');
                var lng=wx.getStorageSync('now_lng')
                this.storeSearch(lat,lng,0,area);
            }
        }
        this.setData({
            areaIndex:index,
            storeIndex:0
        })
    }, 
    getCity:function(){
        let that=this;
        wx.request({        
            url: app.globalData.platUrl+'store/City',
            data:{from:2,},
            success:res=>{
                console.log(res);
                if(res.statusCode==200){
                    let data=res.data;
                    //var city = Object.values(data.city); 
                    var city=[];
                    var citys=data.city;
                    citys.forEach(function(item,index){
                        city[item.id]=item.city;
                    });         
                
                    that.setData({
                        citys:citys,
                        city:city,                                 
                    })
                }else{
                   wx.showLoading({
                     title: '系统错误',
                   }) 
                }
            }
            })
    }, 
    getIndex:function(lat,lng,city,area){
        let that = this; 
        var user=this.data.user;
        var open=this.data.open;
        var user_id=user.id;
        var open_id=open.user_id;
        console.log(user_id)
     // user_id=41;
        var parent_id = wx.getStorageSync('parent_id');
        console.log('city=>'+city+'area=>'+area)
        console.log('user_id=>'+user_id)  
        wx.request({
          url: app.globalData.platUrl+'store/stores',
          data:{from:2,user_id:user_id,open_id:open_id,parent_id:parent_id,lat:lat,lng:lng,city:city,area:area},
          success:res=>{
            console.log('---------------index getIndex---------------')
              console.log(res)
             if(res.statusCode==200){
                 let data=res.data;
                that.setData({
                list:data.list,  
                store:data.store,
                shareTitle:data.shareTitle,
                shareLogo:data.shareLogo,
                //shareIndex:data.shareIndex,
               // backgroud:data.backgroud
                })
             }
          }
        })
     },
     storeSearch:function(lat,lng,city,area){
        let that = this; 
        var open=this.data.open;
        var user_id=open.user_id;
       // user_id=37;
        var parent_id = wx.getStorageSync('parent_id');
        console.log('city=>'+city+'area=>'+area)
        console.log('user_id=>'+user_id)  
        wx.request({
          url: app.globalData.platUrl+'store/storeSearch',
          data:{from:2,user_id:user_id,parent_id:parent_id,lat:lat,lng:lng,city:city,area:area},
          success:res=>{
            console.log('---------------my---------------')
              console.log(res)
             if(res.statusCode==200){
                 let data=res.data;
                that.setData({
                list:data.list,  
                store:data.store,
                shareTitle:data.shareTitle,
               shareLogo:data.shareLogo,
                //shareIndex:data.shareIndex,
               // backgroud:data.backgroud
                })
             }
          }
        })
     },
     bindLetter:function(e){
      console.log(e);
     var total=e.currentTarget.dataset.total;
      var id=e.currentTarget.id;
     //console.log('id='+id+'- total='+total);
     var scrollTop=Number(id)*30+Number(total)*30;
    
     console.log(scrollTop);
     this.setData({
       scrollTop:scrollTop
     })
    }, 
    call:function(e){
        var phone=e.currentTarget.dataset.phone;
        wx.makePhoneCall({
          phoneNumber: phone,
        })
  
    },
    gotoNavigation:function(e){
        console.log(e);
      var position=e.currentTarget.dataset.position;
      var lat=e.currentTarget.dataset.lat;
      var lnt=e.currentTarget.dataset.lnt;
      var address=e.currentTarget.dataset.address;
      wx.navigateTo({
         url: '../map/navigation?position='+position+"&latitude="+lat+"&longitude="+lnt+"&address="+address,
      })
    },
    goBack:function(){
        wx.navigateBack();
      },
    gotoStore(e){
        var id=e.currentTarget.dataset.id;
        var title=e.currentTarget.dataset.title;
        var role=e.currentTarget.dataset.role;
        console.log(e);
        wx.setStorageSync('role', role)
        if(role==2){
            wx.reLaunch({
                url: '/pages/coupon/index?id='+id+'&title='+title,
              })
        }else{
            wx.reLaunch({
                url: '/pages/coupon/index?id='+id+'&title='+title,
              })
        }
        
    },  
    goShopcart:function(){
        wx.reLaunch({
              url: '../shopcart/index',
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
         //this.getIndex();
         //this.getCity(1);
         var store_id=wx.getStorageSync('store_id');  
         if(store_id==0){
            var role=0;
            var tabIndex=0; 
         }else{
            var role=1;
            var tabIndex=0;
         }
        var  tab = wx.getStorageSync('tabBar');  
        tabService.updateTabArray(this,tab);
            wx.setStorageSync('role',role);    
            this.update(role)
            tabService.updateIndex(this, tabIndex);
        
         this.getCity(); 
         this.getLocation();
       },
      update(role) {     
         tabService.updateRole(this, role);
     },

    getDistance:function(latitude1,longitude1,latitude2,longitude2){
        let that=this;
        console.log('latitude1:'+latitude1+' longitude1:'+longitude1+' latitude2:'+latitude2+' longitude2:'+longitude2);
        qqmapsdk.calculateDistance({
          mode:'driving',
          from:{
            latitude:latitude1,
            longitude:longitude1
          },
          to:[{
            latitude:latitude2, 
            longitude:longitude2
          }],
          success:function(res,data){
              console.log(data);
              var distance=data.distance[0]/1000;
              that.setData({
                distance:distance
              })
          }
        })
      },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },
    onShareTimeline(){
        //console.log(e);
        var title = this.data.shareTitle;
        var shareLogo = this.data.shareLogo;
        var open = wx.getStorageSync('open');
        var parent_id=open.user_id;
        var store_id = wx.getStorageSync('store_id');
         this.setData({
           share:true
         });
         console.log(shareLogo);
         console.log(title);
         return{
           title: title,                 
           query: 'parent_id='+parent_id+'&store_id'+store_id,        
           imageUrl:shareLogo      
           }
       },
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        var more=this.data.more;
        var page =this.data.page;
        if(more==1){
           // page=parseInt(page)+1;
           // this.getCity(page)
        }else{
            console.log('no more');
        } 
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage(e) {
        var open=wx.getStorageSync('open');
        var parent_id=open.user_id;
        var that = this;
        var title=this.data.shareTitle;
        var shareLogo=this.data.shareLogo;
        var store_id=wx.getStorageSync('store_id');
   　　var shareObj = {
   　　　　title: title,    
   　　　　path: '/pages/index/index?parent_id='+parent_id+'&store_id'+store_id,  
   　　　　imageUrl: shareLogo 
   　　　
   　　}
   　　// 来自页面内的按钮的转发
   　　if( e.from == 'button' ){
     　　　shareObj.title=title;
   　　　　shareObj.path = '/pages/index/index?parent_id='+parent_id+'&store_id'+store_id;
   　　}
   console.log(shareObj);
   　　// 返回shareObj
   　　return shareObj;
    }
})